package com.fs.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.common.pojo.CheckNote;
import com.fs.common.pojo.CheckRecipes;
import com.fs.common.pojo.Health;
import com.fs.common.service.CheckNoteService;
import com.fs.common.vo.MapVo;
import com.fs.common.vo.RecipesVo;
import com.fs.common.vo.ReportVo;
import com.fs.common.vo.WeekRecipesVo;
import com.fs.common.yzMapper.CheckNoteMapper;
import com.fs.common.yzMapper.CheckRecipesMapper;
import com.fs.common.yzMapper.HealthMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author DeveloperKK
 * @desc
 * @creationTime 2019-08-28 09:25
 * @projectName yuezi-menu
 * @packageName com.fs.common.service.impl
 */
@Service
public class CheckNoteServiceImpl implements CheckNoteService {

    @Autowired
    private CheckRecipesMapper checkRecipesMapper;

    @Autowired
    private HealthMapper healthMapper;

    @Autowired
    CheckNoteMapper checkNoteMapper;

    @Override
    public List<WeekRecipesVo> getRecipes(String checkId) {
        List<WeekRecipesVo> list = new ArrayList<>();
        if(StringUtils.isNotBlank(checkId)){
            for (int i = 1; i <= 4; i++) {
                QueryWrapper<CheckRecipes> wrapper = new QueryWrapper<>();
                wrapper.eq("check_id",checkId);
                wrapper.orderByAsc("eat_date");
                wrapper.eq("week",i);
                List<CheckRecipes> checkRecipes = checkRecipesMapper.selectList(wrapper);
                if(!CollectionUtils.isEmpty(checkRecipes)){
                    WeekRecipesVo weekRecipesVo = new WeekRecipesVo();
                    weekRecipesVo.setStartTime(DateUtils.formatDate(checkRecipes.get(0).getEatDate(),"yyyy-MM-dd"));
                    weekRecipesVo.setEndTime(DateUtils.formatDate(checkRecipes.get(checkRecipes.size()-1).getEatDate(),"yyyy-MM-dd"));
                    List<RecipesVo> recipesVos = new ArrayList<>();
                    String eatTime = "";
                    RecipesVo recipesVo = null;
                    for (int i1 = 0; i1 < checkRecipes.size(); i1++) {
                        CheckRecipes checkRecipe = checkRecipes.get(i1);
                        String date = DateUtils.formatDate(checkRecipe.getEatDate(), "yyyy-MM-dd");
                        if(StringUtils.isBlank(eatTime) || !date.equals(eatTime)){
                            if(null != recipesVo){
                                recipesVos.add(recipesVo);
                            }
                            eatTime = date;
                            recipesVo = new RecipesVo();
                            recipesVo.setTime(date);
                        }
                        setRecipes(recipesVo,checkRecipe);
                        if(i1 == (checkRecipes.size()-1)){
                            recipesVos.add(recipesVo);
                        }
                    }
                    weekRecipesVo.setRecipess(recipesVos);
                    list.add(weekRecipesVo);
                }
            }
        }
        return list;
    }


    /**
     * 获取舌诊，面诊，问卷等结果
     * @param checkNote
     * @return
     */
    @Override
    public Map<String,ReportVo> parseReport(CheckNote checkNote){
        String checkJson = checkNote.getCheckJson();
        if (StringUtils.isNotBlank(checkJson)) {
            Map<String,Object> map = JSON.parseObject(checkJson,Map.class);
            if (map != null && map.containsKey(ReportVo.JSON_KEY)) {
                List<Map<String,Object>> rvList = (List<Map<String,Object>>)map.get(ReportVo.JSON_KEY);
                Map<String,ReportVo> rvMap = new HashMap<>();
                for (Map<String,Object> obj : rvList) {
                    ReportVo rv = JSON.parseObject(JSON.toJSONString(obj),ReportVo.class);
                    //图片未正常扫描,结果信息-1转为空白字符串
                    if ("-1".equals(rv.getResult())){
                        rv.setResult("");
                    }
//                    if (rv.getJcStatus() != null && rv.getJcStatus() == 1 && rv.getSdkStatus() ==1) {
                    // 1:面诊，2舌诊，3问卷
                    switch (rv.getType()) {
                        case 1:
                            rvMap.put("face",rv);
                            break;
                        case 2:
                            rvMap.put("tongue",rv);
                            break;
                        default:
                            break;
                    }
//                    }
                }
                return rvMap;
            }
        }
        return null;
    }

    /**
     * 根据日期获取问卷数量
     * @return
     */
    /*@Override
    public List<Map> getCountForDate(List<String> dayList) {
        List<Map> list = new ArrayList<>();
        for (int i = 0; i < dayList.size()-1;i++){
            String day = dayList.get(i);
            int checkNoteCount = checkNoteMapper.findCheckNoteForDate(day + " 00:00:00", day + " 23:59:59");
            Map<String, Object> map = new HashMap<>();
            map.put("toDay",day);
            map.put("checkNoteCount",checkNoteCount);
            list.add(map);
        }
        return list;
    }*/

    /**
     * 查询问卷的地址信息和数量
     * @return
     */
    @Override
    public List<MapVo> getAddressCount() {
        ArrayList<MapVo> list = new ArrayList<>();
        List<CheckNote> checkNotes = checkNoteMapper.selectList(null);
        list.add(new MapVo("青海",0));
        list.add(new MapVo("宁夏",0));
        list.add(new MapVo("海南",0));
        list.add(new MapVo("甘肃",0));
        list.add(new MapVo("贵州",0));
        list.add(new MapVo("新疆",0));
        list.add(new MapVo("云南",0));
        list.add(new MapVo("重庆",0));
        list.add(new MapVo("吉林",0));
        list.add(new MapVo("山西",0));
        list.add(new MapVo("天津",0));
        list.add(new MapVo("江西",0));
        list.add(new MapVo("广西",0));
        list.add(new MapVo("陕西",0));
        list.add(new MapVo("黑龙江",0));
        list.add(new MapVo("内蒙古",0));
        list.add(new MapVo("安徽",0));
        list.add(new MapVo("北京",0));
        list.add(new MapVo("福建",0));
        list.add(new MapVo("上海",0));
        list.add(new MapVo("湖北",0));
        list.add(new MapVo("湖南",0));
        list.add(new MapVo("四川",0));
        list.add(new MapVo("辽宁",0));
        list.add(new MapVo("河北",0));
        list.add(new MapVo("河南",0));
        list.add(new MapVo("浙江",0));
        list.add(new MapVo("江苏",0));
        list.add(new MapVo("山东",0));
        list.add(new MapVo("广东",0));
        list.add(new MapVo("西藏",0));

        int max = 1;
        for (CheckNote checkNote : checkNotes) {   // 遍历查询到的每一个问卷信息
            for (int i = 0;i<list.size();i++){  // 对省份集合遍历
                if (checkNote.getAddress().contains(list.get(i).getName())){  // 如果两个循环 地址有重复，则对list地址集合的value进行+1
                    int value = list.get(i).getValue();
                    list.get(i).setValue(value+1);
                    if (value + 1 > max){   // max为地图显示颜色高亮的参考值，取集合中value的最大值
                        max = value+1;
                    }
                }
            }
        }
        list.add(new MapVo("max",max));
        return list;
    }


    private void setRecipes(RecipesVo recipes,CheckRecipes checkRecipe){
        if(null != recipes && null != checkRecipe){
            switch (checkRecipe.getMeal()){
                case "早餐":
                    recipes.getBreakfast().add(checkRecipe);
                    break;
                case "中餐":
                    recipes.getLunch().add(checkRecipe);
                    break;
                case "晚餐":
                    recipes.getDinner().add(checkRecipe);
                    break;
                case "加餐":
                    recipes.getMealAddition().add(checkRecipe);
                    break;
            }
        }
    }

    @Override
    public Map<String, String> getAdviseAndAvoid(String constitution, String adviseFood) {
        Map<String, String> rtn = null;
        if (StringUtils.isNotBlank(constitution)){
            List<Health> healthList = healthMapper.selectList(Wrappers.emptyWrapper());
            Set<String> adviseFoods = new HashSet<>();
            Set<String> avoidFoods = new HashSet<>();
            List<String> adviseFoodsList = new ArrayList<>();

            for (Health h : healthList){
                if (constitution.contains(h.getName())){
                    //宜吃
                    String advises = h.getAdvise();
                    addFoods(advises, adviseFoods);
                    //忌口
                    String avoid = h.getAvoid();
                    addFoods(avoid, avoidFoods);
                }
            }
            //去除宜吃中的忌口食物
            for (String af : adviseFoods){
                if (!avoidFoods.contains(af)) {
                    adviseFoodsList.add(af);
                }
            }
            rtn = new HashMap<>();
            String advises = StringUtils.join(adviseFoodsList, "、");
            StringBuilder newAdvise = new StringBuilder();
            //宜吃调整 优先显示指定食材
            String[] adviseFoodArr = adviseFood.split("、");
            advises = "、" + advises + "、";
            for (String ad : adviseFoodArr){
                if (StringUtils.isNotBlank(ad) && advises.contains(ad)){
                    advises = advises.replace("、"+ad+"、" , "、");
                    newAdvise.append("、").append(ad);
                }
            }
            newAdvise.append(advises);
            //去掉最后一个、
            newAdvise.deleteCharAt(newAdvise.length()-1);
            //去掉第一个、
            newAdvise.deleteCharAt(0);
            rtn.put("advises", newAdvise.toString());
            rtn.put("avoid", StringUtils.join(avoidFoods, "、"));
        }
        return rtn;
    }

    private void addFoods(String sourceFoods, Set<String> targetSet){
        if (StringUtils.isNotBlank(sourceFoods)){
            sourceFoods = sourceFoods.replace("等","").replace("。", "");
            String[] foodArr = sourceFoods.split("、");
            targetSet.addAll(Arrays.asList(foodArr));
        }
    }

}
